<template>
  <div class="main user-layout-register">
    <a-form ref="formRegister" :form="form" id="formRegister">
      <h3>用户注册</h3>

      <a-form-item>
        <a-input size="large" placeholder="请输入手机号" v-decorator="['mobile', {rules: [{ required: true, message: $t('user.phone-number.required'), pattern: /^1[3456789]\d{9}$/ }], validateTrigger: ['blur'] }]">
          <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-item>

      <a-row :gutter="16">
        <a-col class="gutter-row" :span="16">
          <a-form-item>
            <a-input size="large" type="text" :placeholder="$t('user.login.mobile.verification-code.placeholder')" v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码' }, { validator: this.handleSmsCaptcha }], validateTrigger: 'blur'}]">
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="8">
          <a-button
            class="getCaptcha"
            size="large"
            :disabled="state.smsSendBtn"
            @click.stop.prevent="getCaptcha"
            v-text="!state.smsSendBtn && $t('user.register.get-verification-code')||(state.time+' s')"></a-button>
        </a-col>
      </a-row>

      <a-form-item>
        <a-input-password
          size="large"
          placeholder="请输入密码"
          v-decorator="['password', {rules: [{ required: true, message: $t('user.password.required') }, { validator: this.handlePassword }], validateTrigger: ['change', 'blur']}]"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input-password>
      </a-form-item>

      <a-form-item>
        <a-input-password
          size="large"
          placeholder="确认密码"
          v-decorator="['password2', {rules: [{ required: true, message: $t('user.password.required') }, { validator: this.handlePasswordCheck }], validateTrigger: ['change', 'blur']}]"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input-password>
      </a-form-item>

      <a-form-item class="last-item">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="register-button"
          :loading="registerBtn"
          @click.stop.prevent="handleSubmit"
          :disabled="registerBtn">{{ $t('user.register.register') }}
        </a-button>
        <router-link class="login" :to="{ name: 'login' }">{{ $t('user.register.sign-in') }}</router-link>
      </a-form-item>

    </a-form>
  </div>
</template>

<script>
import {
  getSmsCaptcha,
  checkSmsCaptcha,
  register
} from '@/api/login'
import { deviceMixin } from '@/store/device-mixin'
// import { scorePassword } from '@/utils/util'

export default {
  name: 'Register',
  mixins: [deviceMixin],
  data () {
    return {
      form: this.$form.createForm(this),
      state: {
        time: 60,
        level: 0,
        smsSendBtn: false
      },
      registerBtn: false
    }
  },
  methods: {
    handleSmsCaptcha (rule, value, callback) {
      const phoneNum = this.form.getFieldValue('mobile')
      const smscode = this.form.getFieldValue('captcha')
      if (!phoneNum || !smscode) callback()
      checkSmsCaptcha({ phoneNum, smscode }).then(res => {
        if (res.success) {
          callback()
        } else {
          callback(new Error(res.message))
        }
      })
    },

    handlePassword (rule, value, callback) {
      if (value === '') {
       return callback()
      }
      const reg = /^[a-zA-Z][a-zA-Z0-9.]{5,11}$/
      if (!reg.test(value)) callback(new Error('请输入字母开头的，字母、数字、小数点、6-12位的组合'))
      callback()
    },

    handlePasswordCheck (rule, value, callback) {
      const password = this.form.getFieldValue('password')
      if (value === undefined) {
        callback(new Error(this.$t('user.password.required')))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error(this.$t('user.password.twice.msg')))
      }
      callback()
    },

    handleSubmit () {
      this.form.validateFields({ force: true }, (err, values) => {
        if (!err) {
          console.log('验证成功')
          console.log(values)
          register({
            phone: values.mobile,
            password: values.password
          }).then(res => {
            if (res.success) {
              this.$notification['success']({
                message: '成功',
                description: '注册成功，赶快去完善资料吧~'
              })
            }
          }).catch(err => {
            this.$notification['error']({
              message: '失败',
              description: err.message
            })
          })
        }
      })
    },

    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state, $message, $notification } = this

      validateFields(['mobile'], { force: true },
        (err, values) => {
          if (!err) {
            state.smsSendBtn = true

            const interval = window.setInterval(() => {
              if (state.time-- <= 0) {
                state.time = 60
                state.smsSendBtn = false
                window.clearInterval(interval)
              }
            }, 1000)

            const hide = $message.loading('验证码发送中..', 0)

            getSmsCaptcha({ phoneNum: values.mobile }).then(res => {
              setTimeout(hide, 2500)
              $notification['success']({
                message: '成功',
                description: '验证码发送成功，请前往手机查看',
                duration: 8
              })
            }).catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
          }
        }
      )
    },

    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.registerBtn = false
    }
  }
}
</script>
<style lang="less">
  .user-register {

    &.error {
      color: #ff0000;
    }

    &.warning {
      color: #ff7e05;
    }

    &.success {
      color: #52c41a;
    }

  }

  .user-layout-register {
    .ant-input-group-addon:first-child {
      background-color: #fff;
    }
  }
</style>
<style lang="less" scoped>
  .user-layout-register {

    & > h3 {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
      font-size: 14px;
    }

    .register-button {
      width: 50%;
    }

    .login {
      float: right;
      line-height: 40px;
    }
  }
  h3 {
    font-size: 22px;
    margin-bottom: 18px;
    line-height: 1;
    text-align: center;
  }
  .last-item {
    margin: 0 !important;
  }
</style>
